package com.jmeter.functions;

import com.shenbianyun.bosskgpay.constant.MerInfoConstant;
import com.shenbianyun.bosskgpay.utils.Base64Utils;
import com.shenbianyun.bosskgpay.utils.DESUtils;
import com.shenbianyun.bosskgpay.utils.RSAUtils;
import org.apache.jmeter.engine.util.CompoundVariable;
import org.apache.jmeter.functions.AbstractFunction;
import org.apache.jmeter.functions.InvalidVariableException;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.samplers.Sampler;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author yvan
 * @Date 2021/11/22 11:40:19
 * @Description //业务参数加密后进行sign加密
 **/



public class SignFunctions extends AbstractFunction {

    public static String key ="__SignJmeter";
    public static List<String> params = new LinkedList();
    static {
        params.add("请输入要加密的json串");
    }
    public String reqData;


    @Override
    public String execute(SampleResult sampleResult, Sampler sampler) throws InvalidVariableException {
        String reqDataEncrypt;
        String signEncrypt;
        try {
            //先加密，在用加密后的字符串进行sign
            byte[] bs = DESUtils.encrypt(reqData.getBytes(MerInfoConstant.CHARSET_UTF_8),MerInfoConstant.INTER_KEY);
            reqDataEncrypt = Base64Utils.encodeToString(bs);
            signEncrypt = RSAUtils.sign(reqDataEncrypt, MerInfoConstant.MER_PRIVATE_KEY);
            System.out.println(signEncrypt);
        } catch (Exception e) {
            e.printStackTrace();
            signEncrypt = "Sign加密失败";
        }
        return signEncrypt;
    }

    @Override
    public void setParameters(Collection<CompoundVariable> collection) throws InvalidVariableException {
        Object[] objects = collection.toArray();
        reqData= ((CompoundVariable) objects[0]).execute();
    }

    @Override
    public String getReferenceKey() {
        return key;
    }

    @Override
    public List<String> getArgumentDesc() {
        return params;
    }


}
